package com.itheima.health.controller;


import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetmealService;
import com.itheima.health.utils.QiniuUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {

    @Autowired
    private SetmealService setmealService;
    @Autowired
    private QiniuUtils qiniuUtils;

    @GetMapping("findPage")
    public Result findPage(QueryPageBean queryPageBean) {

        //查询到的数据                                       查询条件
        PageResult pageResult = setmealService.findPage(queryPageBean);
        //封装统一返回对象 对前端进行响应
        return new Result(true, MessageConst.QUERY_SETMEAL_SUCCESS, pageResult);
    }

    @PostMapping("/add")
    public Result add(@RequestParam List<Integer> checkgroupIds, @RequestBody Setmeal setmeal) {
        //存入基本信息
        setmealService.add(setmeal);
        //获取到套餐id
        Integer id = setmeal.getId();
        for (Integer checkgroupId : checkgroupIds) {
            //存入关联信息
            setmealService.addcheckgroupIdAndSetmealId(id, checkgroupId);
        }
        return new Result(true, MessageConst.ADD_SETMEAL_SUCCESS);
    }

    @PostMapping("upload")
    public Result upload(MultipartFile imgFile) {
        try {
            //获取名字先 这是图片原始名字
            String originalFilename = imgFile.getOriginalFilename();
            //最后一次点的索引
            int index = originalFilename.lastIndexOf(".");
            //截取后缀名
            String oldName = originalFilename.substring(index);
            //随机生成文件名称
            String name = UUID.randomUUID().toString() + oldName;
            //上传七牛云
            qiniuUtils.upload2Qiniu(imgFile.getInputStream(), name);
            //
            String urlPrefix = qiniuUtils.getUrlPrefix();
            String newName = urlPrefix + name;
            return new Result(true, MessageConst.PIC_UPLOAD_SUCCESS, newName);
        } catch (IOException e) {
            throw new BusinessRuntimeException("图片上传失败");
        }


    }


}
